package com.kongyz.zuulservice.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @Project : springcloudlearn
 * @PackageName : com.kongyz.zuulservice.filter
 * @Company 
 * @Description:
 * @Author Kongyz on 2019-09-24 16:52.
 */
@Component
public class MyFilter extends ZuulFilter {
    private static Logger logge= LoggerFactory.getLogger(MyFilter.class);

    /**
     * 功能描述:filterType：返回一个字符串代表过滤器的类型，在zuul中定义了四种不同生命周期的过滤器类型，具体如下：
     *      pre：路由之前
     *      routing：路由之时
     *      post： 路由之后
     *      error：发送错误调用
     * @auther: Kongyz  2019-09-24 16:53
     */
    @Override
    public String filterType() {
        return "pre";
    }

    /**
     * 过滤对顺序
     * @auther: Kongyz  2019-09-24 16:54
     */
    @Override
    public int filterOrder() {
        return 0;
    }

    /**
     * 这里可以写逻辑判断，是否要过滤，
     * 返回值为true，永远过滤
     * @auther: Kongyz  2019-09-24 16:55
     */
    @Override
    public boolean shouldFilter() {
        return false;
    }

    /**
     * 过滤的具体逻辑。可以复杂，也可以包含sql，nosql去判断该请求是否有权限
     * @auther: Kongyz  2019-09-24 16:56
     */
    @Override
    public Object run() throws ZuulException {
        RequestContext ctx= RequestContext.getCurrentContext();
        HttpServletRequest request= ctx.getRequest();
        logge.info(String.format("%s >>> %s",request.getMethod(),request.getRequestURL().toString()));
        Object accessToken=request.getParameter("token");
        if(accessToken==null){
            logge.warn("token 为空");
            ctx.setSendZuulResponse(false);
            ctx.setResponseStatusCode(401);
            try {
                ctx.getResponse().setCharacterEncoding("UTF-8");
                ctx.getResponse().getWriter().write("token 为空");
            } catch (IOException e) {
                logge.error("返回出错",e);
            }
            return null;
        }
        logge.info("MyFilter，过滤成功");
        return null;
    }
}
